package com.zxw.article.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxw.article.mapper.ArticleMapper;
import com.zxw.article.service.ArticleCategoryService;
import com.zxw.article.service.ArticleService;
import com.zxw.article.service.TagService;
import com.zxw.common.entity.article.ArticleEntity;
import com.zxw.common.entity.article.ArticleListQuery;
import com.zxw.common.entity.article.ArticleQuery;
import com.zxw.common.entity.article.ArticleVO;
import com.zxw.common.entity.article.count.ArticleCategoryCountVO;
import com.zxw.common.entity.category.ArticleCategoryEntity;
import com.zxw.common.entity.tag.TagEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章信息表 服务实现类
 * </p>
 *
 * @author zhanxuewei
 * @since 2022-09-19
 */
@Service
@Slf4j
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, ArticleEntity> implements ArticleService {

    @Autowired
    private ArticleCategoryService articleCategoryService;
    @Autowired
    private TagService tagService;
    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 添加
     *
     * @param articleQuery ArticleQuery
     * @return 是否成功 true|false
     */
    @Override
    public boolean save(ArticleQuery articleQuery) {
        ArticleEntity articleEntity = new ArticleEntity();
        BeanUtils.copyProperties(articleQuery, articleEntity);
        articleEntity.setId(null);
        articleEntity.setStatus("1");
        articleEntity.setCountScan(0);
        return super.save(articleEntity);
    }

    /**
     * 批量添加
     *
     * @param list List<ArticleQuery>
     * @return 是否成功 true|false
     */
    @Override
    public boolean saveBatch(List<ArticleQuery> list) {
        List<ArticleEntity> collect = list.stream().map(item -> {
            ArticleEntity articleEntity = new ArticleEntity();
            BeanUtils.copyProperties(item, articleEntity);
            articleEntity.setId(null);
            articleEntity.setStatus("1");
            articleEntity.setCountScan(0);
            return articleEntity;
        }).collect(Collectors.toList());
        return super.saveBatch(collect);
    }

    /**
     * 根据ID集合批量删除
     *
     * @param ids id集合
     * @return 是否成功 true|false
     */
    @Override
    public boolean removeByIds(List<String> ids) {
        return super.removeByIds(ids);
    }

    /**
     * 根据ID修改
     *
     * @param articleQuery ArticleQuery
     * @return 是否成功 true|false
     */
    @Override
    public boolean updateById(ArticleQuery articleQuery) {
        ArticleEntity articleEntity = new ArticleEntity();
        BeanUtils.copyProperties(articleQuery, articleEntity);
        return super.updateById(articleEntity);
    }

    /**
     * 根据ID查询数据
     *
     * @param id ID
     * @return ArticleDO
     */
    @Override
    public ArticleEntity getById(String id) {
        return super.getById(id);
    }

    /**
     * 条件分页查询
     *
     * @param articleListQuery ArticleListQuery
     * @return IPage<ArticleDO>
     */
    @Override
    public IPage<ArticleEntity> list(ArticleListQuery articleListQuery) {
        IPage<ArticleEntity> pageInfo = new Page<>(articleListQuery.getCurrent(), articleListQuery.getSize());
        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ArticleEntity::getStatus, 1)
                .orderByDesc(ArticleEntity::getCreateTime);
        return super.page(pageInfo, queryWrapper);
    }

    @Override
    public IPage<ArticleVO> pageList(ArticleListQuery articleListQuery) {
        IPage<ArticleEntity> pageInfo = new Page<>(articleListQuery.getCurrent(), articleListQuery.getSize());
        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ArticleEntity> lambda = queryWrapper.lambda();
        if (StringUtils.isNotBlank(articleListQuery.getTitle())) {
            lambda.like(ArticleEntity::getTitle, articleListQuery.getTitle());
        }
        if (StringUtils.isNotBlank(articleListQuery.getAuthor())) {
            lambda.like(ArticleEntity::getAuthor, articleListQuery.getAuthor());
        }

        if (StringUtils.isNotBlank(articleListQuery.getShortLine())) {
            lambda.like(ArticleEntity::getShortLine, articleListQuery.getShortLine());
        }
        if (StringUtils.isNotBlank(articleListQuery.getCategoryId())) {
            lambda.eq(ArticleEntity::getCategoryId, articleListQuery.getCategoryId());
        }
        if (Objects.nonNull(articleListQuery.getIsCarousel())) {
            lambda.eq(ArticleEntity::getIsCarousel, articleListQuery.getIsCarousel());
        }
        if (Objects.nonNull(articleListQuery.getIsRecommend())) {
            lambda.eq(ArticleEntity::getIsRecommend, articleListQuery.getIsRecommend());
        }
        if (Objects.nonNull(articleListQuery.getIsOriginal())) {
            lambda.eq(ArticleEntity::getIsOriginal, articleListQuery.getIsOriginal());
        }
        if (Objects.nonNull(articleListQuery.getIsTop())) {
            lambda.eq(ArticleEntity::getIsTop, articleListQuery.getIsTop());
        }
        if (StringUtils.isNotBlank(articleListQuery.getAuthor())) {
            lambda.like(ArticleEntity::getAuthor, articleListQuery.getAuthor());
        }
        if (StringUtils.isNotBlank(articleListQuery.getShortLine())) {
            lambda.like(ArticleEntity::getShortLine, articleListQuery.getShortLine());
        }
        if (StringUtils.isNotBlank(articleListQuery.getCategoryId())) {
            lambda.eq(ArticleEntity::getCategoryId, articleListQuery.getCategoryId());
        }
        if (Objects.nonNull(articleListQuery.getIsCarousel())) {
            lambda.eq(ArticleEntity::getIsCarousel, articleListQuery.getIsCarousel());
        }
        if (Objects.nonNull(articleListQuery.getIsRecommend())) {
            lambda.eq(ArticleEntity::getIsRecommend, articleListQuery.getIsRecommend());
        }
        if (Objects.nonNull(articleListQuery.getIsOriginal())) {
            lambda.eq(ArticleEntity::getIsOriginal, articleListQuery.getIsOriginal());
        }
        if (Objects.nonNull(articleListQuery.getIsTop())) {
            lambda.eq(ArticleEntity::getIsTop, articleListQuery.getIsTop());
        }
        lambda.orderByDesc(ArticleEntity::getCreateTime);
        IPage<ArticleEntity> page = super.page(pageInfo, queryWrapper);
        return page.convert(articleEntity -> {
            ArticleVO articleVO = new ArticleVO();
            BeanUtils.copyProperties(articleEntity, articleVO);
            // 文章分类名称
            ArticleCategoryEntity articleCategoryEntity = this.articleCategoryService.getById(articleEntity.getCategoryId());
            articleVO.setCategoryName(Objects.nonNull(articleCategoryEntity) ? articleCategoryEntity.getName() : "");
            // 文章标签名称
            if (StringUtils.isNotBlank(articleEntity.getTagIds())) {
                String[] tagIds = articleEntity.getTagIds().split(",");
                List<TagEntity> tagEntities = tagService.listByIds(Arrays.asList(tagIds));
                if (CollUtil.isNotEmpty(tagEntities)) {
                    List<String> tagNames = tagEntities.stream().map(TagEntity::getName).collect(Collectors.toList());
                    articleVO.setTagNames(StringUtils.join(tagNames, ","));
                }
            }
            return articleVO;
        });
    }


    @Override
    public List<ArticleVO> queryList(ArticleListQuery articleListQuery) {
        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ArticleEntity> lambda = queryWrapper.lambda();
        if (StringUtils.isNotBlank(articleListQuery.getTitle())) {
            lambda.like(ArticleEntity::getTitle, articleListQuery.getTitle());
        }
        if (StringUtils.isNotBlank(articleListQuery.getAuthor())) {
            lambda.like(ArticleEntity::getAuthor, articleListQuery.getAuthor());
        }

        if (StringUtils.isNotBlank(articleListQuery.getShortLine())) {
            lambda.like(ArticleEntity::getShortLine, articleListQuery.getShortLine());
        }
        if (StringUtils.isNotBlank(articleListQuery.getCategoryId())) {
            lambda.eq(ArticleEntity::getCategoryId, articleListQuery.getCategoryId());
        }
        if (Objects.nonNull(articleListQuery.getIsCarousel())) {
            lambda.eq(ArticleEntity::getIsCarousel, articleListQuery.getIsCarousel());
        }
        if (Objects.nonNull(articleListQuery.getIsRecommend())) {
            lambda.eq(ArticleEntity::getIsRecommend, articleListQuery.getIsRecommend());
        }
        if (Objects.nonNull(articleListQuery.getIsOriginal())) {
            lambda.eq(ArticleEntity::getIsOriginal, articleListQuery.getIsOriginal());
        }
        if (Objects.nonNull(articleListQuery.getIsTop())) {
            lambda.eq(ArticleEntity::getIsTop, articleListQuery.getIsTop());
        }
        if (StringUtils.isNotBlank(articleListQuery.getAuthor())) {
            lambda.like(ArticleEntity::getAuthor, articleListQuery.getAuthor());
        }
        if (StringUtils.isNotBlank(articleListQuery.getShortLine())) {
            lambda.like(ArticleEntity::getShortLine, articleListQuery.getShortLine());
        }
        if (StringUtils.isNotBlank(articleListQuery.getCategoryId())) {
            lambda.eq(ArticleEntity::getCategoryId, articleListQuery.getCategoryId());
        }
        if (Objects.nonNull(articleListQuery.getIsCarousel())) {
            lambda.eq(ArticleEntity::getIsCarousel, articleListQuery.getIsCarousel());
        }
        if (Objects.nonNull(articleListQuery.getIsRecommend())) {
            lambda.eq(ArticleEntity::getIsRecommend, articleListQuery.getIsRecommend());
        }
        if (Objects.nonNull(articleListQuery.getIsOriginal())) {
            lambda.eq(ArticleEntity::getIsOriginal, articleListQuery.getIsOriginal());
        }
        if (Objects.nonNull(articleListQuery.getIsTop())) {
            lambda.eq(ArticleEntity::getIsTop, articleListQuery.getIsTop());
        }
        if (Objects.nonNull(articleListQuery.getLimit())) {
            lambda.last("limit " + articleListQuery.getLimit());
        }
        lambda.orderByDesc(ArticleEntity::getCreateTime);
        List<ArticleEntity> list = super.list(queryWrapper);
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(articleEntity -> {
                ArticleVO articleVO = new ArticleVO();
                BeanUtils.copyProperties(articleEntity, articleVO);
                // 文章分类名称
                ArticleCategoryEntity articleCategoryEntity = this.articleCategoryService.getById(articleEntity.getCategoryId());
                articleVO.setCategoryName(Objects.nonNull(articleCategoryEntity) ? articleCategoryEntity.getName() : "");
                // 文章标签名称
                if (StringUtils.isNotBlank(articleEntity.getTagIds())) {
                    String[] tagIds = articleEntity.getTagIds().split(",");
                    List<TagEntity> tagEntities = tagService.listByIds(Arrays.asList(tagIds));
                    if (CollUtil.isNotEmpty(tagEntities)) {
                        List<String> tagNames = tagEntities.stream().map(TagEntity::getName).collect(Collectors.toList());
                        articleVO.setTagNames(StringUtils.join(tagNames, ","));
                    }
                }
                return articleVO;
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    @Override
    public List<ArticleVO> queryScanRankList(Integer limit) {
        QueryWrapper<ArticleEntity> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ArticleEntity> lambda = queryWrapper.lambda();
        lambda.orderByDesc(ArticleEntity::getCountScan);
        lambda.last("limit " + limit);
        List<ArticleEntity> list = super.list(queryWrapper);
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(articleEntity -> {
                ArticleVO articleVO = new ArticleVO();
                BeanUtils.copyProperties(articleEntity, articleVO);
                // 文章分类名称
                ArticleCategoryEntity articleCategoryEntity = this.articleCategoryService.getById(articleEntity.getCategoryId());
                articleVO.setCategoryName(Objects.nonNull(articleCategoryEntity) ? articleCategoryEntity.getName() : "");
                // 文章标签名称
                if (StringUtils.isNotBlank(articleEntity.getTagIds())) {
                    String[] tagIds = articleEntity.getTagIds().split(",");
                    List<TagEntity> tagEntities = tagService.listByIds(Arrays.asList(tagIds));
                    if (CollUtil.isNotEmpty(tagEntities)) {
                        List<String> tagNames = tagEntities.stream().map(TagEntity::getName).collect(Collectors.toList());
                        articleVO.setTagNames(StringUtils.join(tagNames, ","));
                    }
                }
                return articleVO;
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    @Override
    public ArticleVO detail(String id) {
        ArticleEntity articleEntity = this.getById(id);
        if (Objects.nonNull(articleEntity)) {
            // 浏览数+1
            Integer countScan = articleEntity.getCountScan();
            articleEntity.setCountScan(countScan + 1);
            this.updateById(articleEntity);


            ArticleVO articleVO = new ArticleVO();
            BeanUtils.copyProperties(articleEntity, articleVO);
            // 文章分类名称
            ArticleCategoryEntity articleCategoryEntity = this.articleCategoryService.getById(articleEntity.getCategoryId());
            articleVO.setCategoryName(Objects.nonNull(articleCategoryEntity) ? articleCategoryEntity.getName() : "");
            // 文章标签名称
            if (StringUtils.isNotBlank(articleEntity.getTagIds())) {
                String[] tagIds = articleEntity.getTagIds().split(",");
                List<TagEntity> tagEntities = tagService.listByIds(Arrays.asList(tagIds));
                if (CollUtil.isNotEmpty(tagEntities)) {
                    List<String> tagNames = tagEntities.stream().map(TagEntity::getName).collect(Collectors.toList());
                    articleVO.setTagNames(StringUtils.join(tagNames, ","));
                }
            }
            return articleVO;
        }
        return null;
    }

    /**
     * 分组统计
     *
     * @return
     */
    @Override
    public List<ArticleCategoryCountVO> articleCategoryCount() {
        return this.articleMapper.articleCategoryCount();
    }

    /**
     * echarts文章分类统计
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> echartsArticleCategoryCountPie() {
        List<ArticleCategoryCountVO> list = this.articleCategoryCount();
        if (CollUtil.isNotEmpty(list)) {
            return list.stream().map(e -> {
                Map<String, Object> map = new HashMap<>();
                map.put("name", e.getName());
                map.put("value", e.getCount());
                return map;
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }


}
